package com.jinzhi.jzdoor.certificate.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.*;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sms.config.SmsBasicConfigProperties;
import com.jinzhi.sms.support.SmsManager;
import com.jinzhi.sms.support.SmsSender;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.ehcache.Element;
@Slf4j
@Controller
@RequestMapping("/enterprise")
public class EnterpriseController extends BaseController {

    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private OrganizationRolesService organizationRolesService;
    @Autowired
    private MessageplatfromService messageplatfromService;
    @Autowired
    private SmsManager smsSerevice;
    @Autowired
    private SmsManager smsService;
    @Autowired
    private UserService userService;
    private UserRoleService userRoleService;
    @Autowired
    private ExpertsService expertsService;
    @Autowired
    private ExaminationRoomService examinationRoomService;
    @Autowired
    private PersonnelArrangementService personnelArrangementService;
    @Autowired
    private CertificationBatchService certificationBatchService;
    @Autowired
    private CapitalFlowService capitalFlowService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Log("企业注册")
    @GetMapping("/enterpriseAdd")
    @ResponseBody
    public Result<?> selCertificateInfo( OrganizationNewsDO organization,String code,String userName,String password,String name) {
        String  prefix="enterAdd";
//        //判断验证码
        try {
            smsSerevice.verify(prefix, organization.getMobile(), code);
        } catch (Exception e) {
            return Result.fail("验证码错误");
        }

        //查询手机号是否注册
        Wrapper<UserDO> wrapper = new EntityWrapper();
        wrapper.eq("username", userName);
        UserDO user = userService.selectOne(wrapper);
        if(user!=null){
            return Result.fail("用户名已经存在！");
        }

        //查询手机号是否注册
        Wrapper<UserDO> wrapperMobile = new EntityWrapper();
        wrapperMobile.eq("mobile", organization.getMobile());
        UserDO userMobile = userService.selectOne(wrapperMobile);
        if(userMobile!=null){
            return Result.fail("手机号已经绑定！");
        }


        EntityWrapper<OrganizationNewsDO> entityWrapper = new EntityWrapper<>();
        entityWrapper.like("name", organization.getName());
        entityWrapper.eq("type", 5);
        List<OrganizationNewsDO> organizationNewsDOList = organizationNewsService.selectList(entityWrapper);

        if(organizationNewsDOList.size()>0){
            return Result.fail("企业名称已经存在！");

        }
        //   Long l=  this.getUserId();
        //5为招聘企业注册
        organization.setType(5);
        organization.setCreaterDate(new Date());
        organization.setState(0);
        boolean newsDO=   organizationNewsService.insert(organization);
        UserDO userDO = new UserDO();
        userDO.setPassword(password);
        userDO.setUsername(userName);
        userDO.setMobile(organization.getMobile());
        userDO.setMoney(BigDecimal.valueOf(0.0));//默认0元
        userDO.setGmtCreate(new Date());
        userDO.setStatus(1);//默认正常
        userDO.setSex(0L);//默认未知
        userDO.setType(1);
        userDO.setOrgId(organization.getId());
        userDO.setOrgName(name);
        boolean b = userService.insert(userDO);
        organization.setLeadingCadreId(userDO.getId());
        organizationNewsService.updateById(organization);
        EhCacheUtil.put(userDO.getId()+"name",userName);
        EhCacheUtil.put(userDO.getId()+"pass",password);


        userService.insertUserRole(58L, userDO.getId());

        if(newsDO){
            Map map=new HashMap();
            map.put("id",organization.getId());
            map.put("name",organization.getName());
            map.put("mobile",organization.getMobile());
            map.put("enId",userDO.getId());
            //map.put("password",password);
            return Result.ok(map);
        }

        return Result.fail("注册失败，请联系管理员！");

    }

    @Log("登录")
    @PostMapping("/enLogin")
    @ResponseBody
    Result<?> enLogin(String enId) {
        if(EhCacheUtil.get(enId+"name")!=null){
            String username=EhCacheUtil.get(enId+"name").toString();
            String password=EhCacheUtil.get(enId+"pass").toString();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            try {
                subject.login(token);
                return Result.ok();

            } catch (AuthenticationException e) {
                return Result.build(EnumErrorCode.userLoginFail.getCode(), EnumErrorCode.userLoginFail.getMsg());
            }
        }else {
            return Result.fail();
        }

    }


    @GetMapping("/enMain")
    String enMain(Model model , HttpServletRequest req) {


        UserDO userDO = userService.selectById(this.getUserId());
        model.addAttribute("name", userDO.getUsername());
        model.addAttribute("orgName", userDO.getOrgName());

        List<String> roleNames = userRoleService.selroleNameList(this.getUserId());
        model.addAttribute("roleNames", roleNames);
        req.getSession().setAttribute("roleNames" , roleNames);

        EntityWrapper entityWrapper = new EntityWrapper();
        int stuAllNum;
        int eroomAllNum;
        if(roleNames.indexOf("超级用户角色") > -1) {
            stuAllNum = stuSignUpService.selectCount(entityWrapper);
            eroomAllNum = examinationRoomService.selectCount(entityWrapper);

            int orgAllNum = organizationRolesService.selectCount(entityWrapper);
            model.addAttribute("orgAllNum",orgAllNum);

            int expAllNum = expertsService.selectCount(entityWrapper);
            model.addAttribute("expAllNum",expAllNum);

            int stuNoReview = stuSignUpService.selNoReviewAll();
            model.addAttribute("stuNoReview",stuNoReview);
            int orgNoReview = organizationRolesService.selNoReviewAll();
            model.addAttribute("orgNoReview",orgNoReview);
            int expNoReview = expertsService.selNoReviewAll();
            model.addAttribute("expNoReview",expNoReview);
            int eroomNoReview = examinationRoomService.selNoReviewAll();
            model.addAttribute("eroomNoReview",eroomNoReview);
        }else{
            stuAllNum = stuSignUpService.selNoReview(this.getUser().getOrgId());
            eroomAllNum = examinationRoomService.selNoReview(this.getUser().getOrgId());
        }
        model.addAttribute("stuAllNum",stuAllNum);
        model.addAttribute("eroomAllNum",eroomAllNum);

        return "main";
    }

    @Log("企业注册第二步")
    @GetMapping("/enterpriseUserAdd")
    @ResponseBody
    public Result<?> enterpriseUserAdd( OrganizationNewsDO organization) {

//        //查询手机号是否注册
//        Wrapper<UserDO> wrapper = new EntityWrapper();
//        wrapper.eq("mobile", organization.getMobile());
//        UserDO user = userService.selectOne(wrapper);
//        if (user != null) {
//            return Result.fail("手机号码已经绑定！");
//        }

        if (organization.getMobile()==null) {
            return Result.fail("手机号不能为空！");
        }

        OrganizationRolesDO organizationRolesDO=new OrganizationRolesDO();
        organizationRolesDO.setOrgId(organization.getId());
        organizationRolesDO.setRoleType(7);
        organizationRolesDO.setApplicantDate(new Date());
        organizationRolesDO.setCheckerState(0);
        if(organization.getEnId()!=null){
            organizationRolesDO.setApplicantId(Long.valueOf(organization.getEnId()));
        }

        //插入机构角色表
        organizationRolesDO.setEnclosure(organization.getEnclosure());
        organizationRolesService.insert(organizationRolesDO);

        OrganizationNewsDO organizationNewsDO= organizationNewsService.selectById(organization.getId());
        if(organizationNewsDO==null){
            return Result.fail("注册失败，请返回第一步重新注册！");
        }
        organizationNewsDO.setLegalPErson(organization.getLegalPErson());
        organizationNewsDO.setLegalPErsonPhone(organization.getLegalPErsonPhone());
        organizationNewsDO.setPrincipal(organization.getPrincipal());
        organizationNewsDO.setPrincipalPhone(organization.getPrincipalPhone());
        organizationNewsDO.setMailbox(organization.getMailbox());
        organizationNewsDO.setUnitNature(organization.getUnitNature());
        organizationNewsDO.setIndustry(organization.getIndustry());
        organizationNewsDO.setOrgCode(organization.getOrgCode());
        organizationNewsDO.setRegisterMoney(organization.getRegisterMoney());
        organizationNewsDO.setStaffSize(organization.getStaffSize());
        organizationNewsDO.setOrgPhoto(organization.getOrgPhoto());
        organizationNewsDO.setIdCardFront(organization.getIdCardFront());
        organizationNewsDO.setIdCardVerso(organization.getIdCardVerso());
        organizationNewsDO.setAuthorization(organization.getAuthorization());
        organizationNewsDO.setSetDate(organization.getSetDate());
        organizationNewsDO.setIntroduce(organization.getIntroduce());
        organizationNewsDO.setProductIntroduction(organization.getProductIntroduction());
        organizationNewsDO.setAddress(organization.getAddress());
        organizationNewsDO.setUrl(organization.getUrl());
        boolean b=  organizationNewsService.updateById(organizationNewsDO);

        if(b){
            Map map=new HashMap();
            map.put("enId",organization.getEnId());

            return Result.ok(map);
        }
        return Result.fail("失败了！");

    }


    @GetMapping("/enterpriseSend")
    @Log("发送验证码")
    @ApiOperation("发送验证码")
    @ResponseBody
    public Result sendCode(String mobile) {
        String  prefix="enterAdd";
        Object smsDemo = EhCacheUtil.get("enterAdd");
        if(smsDemo == null){
            MessageplatfromDO messageplatfromDO = messageplatfromService.findOneByKv("注册验证码");
            if(messageplatfromDO != null){
                EhCacheUtil.put(prefix,messageplatfromDO.getSmsDemo());
                smsService.enterpriseSend(prefix, mobile,messageplatfromDO.getSmsDemo());
            }else{
                return Result.fail("短信模板错误，请联系管理员！");
            }
        }else{
            smsService.enterpriseSend(prefix, mobile,(String) smsDemo);
        }

        return Result.ok("发送成功");
    }






}
